<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单编号" prop="orderId">
        <el-input v-model="queryParams.orderId" placeholder="请输入工单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="工单状态" prop="statue">
        <el-select v-model="queryParams.statue" placeholder="请选择工单状态" clearable>
          <el-option
            v-for="dict in dict.type.order_statue"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="工单类型" prop="workType">
        <el-select v-model="queryParams.workType" placeholder="请选择工单类型" clearable>
          <el-option v-for="dict in dict.type.order_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
          <el-option v-for="dict in dict.type.order_priority" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="用户号" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发起部门id" prop="startDeptId">
        <el-input
          v-model="queryParams.startDeptId"
          placeholder="请输入发起部门id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发起部门" prop="startDept">
        <el-input
          v-model="queryParams.startDept"
          placeholder="请输入发起部门"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发起人id" prop="startUserId">
        <el-input
          v-model="queryParams.startUserId"
          placeholder="请输入发起人id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发起人" prop="startUser">
        <el-input
          v-model="queryParams.startUser"
          placeholder="请输入发起人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="承办部门di" prop="endDeptId">
        <el-input
          v-model="queryParams.endDeptId"
          placeholder="请输入承办部门di"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="承办部门" prop="endDept">
        <el-input
          v-model="queryParams.endDept"
          placeholder="请输入承办部门"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="承办人id" prop="endUserId">
        <el-input
          v-model="queryParams.endUserId"
          placeholder="请输入承办人id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="承办人" prop="endUser">
        <el-input
          v-model="queryParams.endUser"
          placeholder="请输入承办人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系事项" prop="matter">
        <el-input
          v-model="queryParams.matter"
          placeholder="请输入联系事项"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入工单标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="附件" prop="attachment">
        <el-input
          v-model="queryParams.attachment"
          placeholder="请输入附件"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['service:newWorkOrder:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['service:newWorkOrder:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['service:newWorkOrder:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['service:newWorkOrder:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="newWorkOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="工单编号" align="center" prop="orderId" fixed="left" />
      <el-table-column label="工单状态" align="center" prop="statue">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_statue" :value="scope.row.statue" />
        </template>
      </el-table-column>
      <el-table-column label="工单类型" align="center" prop="workType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_type" :value="scope.row.workType" />
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_priority" :value="scope.row.priority" />
        </template>
      </el-table-column>
      <el-table-column label="用户号" align="center" prop="userId" />
      <el-table-column label="用户名" align="center" prop="userName" />
      <!-- <el-table-column label="发起部门id" align="center" prop="startDeptId" /> -->
      <el-table-column label="发起部门" align="center" prop="startDept" />
      <!-- <el-table-column label="发起人id" align="center" prop="startUserId" /> -->
      <el-table-column label="发起人" align="center" prop="startUser" />
      <!-- <el-table-column label="承办部门di" align="center" prop="endDeptId" /> -->
      <el-table-column label="承办部门" align="center" prop="endDept">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.end_dept" :value="scope.row.endDept" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="承办人id" align="center" prop="endUserId" /> -->
      <!-- <el-table-column label="承办人" align="center" prop="endUser" /> -->
      <el-table-column label="工单标题" align="center" prop="title" />
      <el-table-column label="联系事项" align="center" prop="matter" width="150" />
      <el-table-column label="内容摘要" align="center" prop="content" width="400" />

      <!-- <el-table-column label="附件" align="center" prop="attachment" /> -->

       <el-table-column label="附件" align="center" width="180">
  <template slot-scope="scope">
    <div v-if="scope.row.attachment">
      <!-- 处理多个文件的情况 -->
      <div v-for="(filePath, index) in scope.row.attachment.split(',')" :key="index">
        <el-link type="primary" :underline="false" @click="previewFile(filePath.trim())" class="file-link">
          <i class="el-icon-document"></i>
          {{ getFileName(filePath.trim()) }}
        </el-link>
      </div>
    </div>
    <span v-else>-</span>
  </template>
</el-table-column>

      <el-table-column label="备注" align="center" prop="remark" />
      <!-- <el-table-column label="提交内容" align="center" prop="commitContent" />
      <el-table-column label="提交图片" align="center" prop="commitPic" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.commitPic" :width="50" :height="50"/>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['service:newWorkOrder:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['service:newWorkOrder:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改工作工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="工单编号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入工单编号" />
        </el-form-item> -->
        <!-- <el-form-item label="工单状态" prop="statue">
          <el-select v-model="form.statue" placeholder="请选择工单状态">
            <el-option v-for="dict in dict.type.order_statue" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="工单类型" prop="workType">
          <el-select v-model="form.workType" placeholder="请选择工单类型">
            <el-option v-for="dict in dict.type.order_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级">
            <el-option v-for="dict in dict.type.order_priority" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户号" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户号" />
        </el-form-item>
        <!-- <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item> -->
        <!-- <el-form-item label="发起部门id" prop="startDeptId">
          <el-input v-model="form.startDeptId" placeholder="请输入发起部门id" />
        </el-form-item> -->
        <!-- <el-form-item label="发起部门" prop="startDept">
          <el-input v-model="form.startDept" placeholder="请输入发起部门" />
        </el-form-item> -->
        <!-- <el-form-item label="发起人id" prop="startUserId">
          <el-input v-model="form.startUserId" placeholder="请输入发起人id" />
        </el-form-item> -->
        <!-- <el-form-item label="发起人" prop="startUser">
          <el-input v-model="form.startUser" placeholder="请输入发起人" />
        </el-form-item> -->
        <!-- <el-form-item label="承办部门di" prop="endDeptId">
          <el-input v-model="form.endDeptId" placeholder="请输入承办部门di" />
        </el-form-item> -->
        <el-form-item label="承办部门" prop="endDept">
          <el-select v-model="form.endDept" placeholder="请选择承办部门">
            <el-option v-for="dict in dict.type.end_dept" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="承办人id" prop="endUserId">
          <el-input v-model="form.endUserId" placeholder="请输入承办人id" />
        </el-form-item> -->
        <!-- <el-form-item label="承办人" prop="endUser">
          <el-input v-model="form.endUser" placeholder="请输入承办人" />
        </el-form-item> -->
        <el-form-item label="联系事项" prop="matter">
          <el-input v-model="form.matter" placeholder="请输入联系事项" />
        </el-form-item>
        <el-form-item label="工单标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入工单标题" />
        </el-form-item>
        <el-form-item label="内容摘要" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="附件" prop="attachment">
          <el-input v-model="form.attachment" placeholder="请输入附件" />
        </el-form-item> -->
         <el-form-item label="附件" prop="attachment">
          <file-upload v-model="form.attachment"/>
        </el-form-item>
      

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="提交内容" prop="commitContent">
          <el-input v-model="form.commitContent" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="提交图片" prop="commitPic">
          <image-upload v-model="form.commitPic"/>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listNewWorkOrder, getNewWorkOrder, delNewWorkOrder, addNewWorkOrder, updateNewWorkOrder } from "@/api/service/newWorkOrder";

  export default {
    name: "NewWorkOrder",
    dicts: ['order_statue', 'order_priority', 'order_type', 'end_dept'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 工作工单表格数据
        newWorkOrderList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderId: null,
          statue: 1,
          workType: null,
          priority: null,
          userId: null,
          userName: null,
          startDeptId: null,
          startDept: null,
          startUserId: null,
          startUser: null,
          endDeptId: null,
          endDept: null,
          endUserId: null,
          endUser: null,
          matter: null,
          title: null,
          content: null,
          attachment: null,
          commitContent: null,
          commitPic: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          // statue: [
          //   { required: true, message: "工单状态不能为空", trigger: "change" }
          // ],
          workType: [
            { required: true, message: "工单类型不能为空", trigger: "change" }
          ],
          priority: [
            { required: true, message: "优先级不能为空", trigger: "change" }
          ],
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询工作工单列表 */
      getList() {
        this.loading = true;
        listNewWorkOrder(this.queryParams).then(response => {
          this.newWorkOrderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          orderId: null,
          statue: null,
          workType: null,
          priority: null,
          userId: null,
          userName: null,
          startDeptId: null,
          startDept: null,
          startUserId: null,
          startUser: null,
          endDeptId: null,
          endDept: null,
          endUserId: null,
          endUser: null,
          matter: null,
          title: null,
          content: null,
          attachment: null,
          remark: null,
          commitContent: null,
          commitPic: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加工作工单";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getNewWorkOrder(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改工作工单";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateNewWorkOrder(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.statue = 1;
              this.form.startDept="营销管理部"
              addNewWorkOrder(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除工作工单编号为"' + ids + '"的数据项？').then(function () {
          return delNewWorkOrder(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('service/newWorkOrder/export', {
          ...this.queryParams
        }, `newWorkOrder_${new Date().getTime()}.xlsx`)
      }

      ,



      

      // 从文件路径中提取文件名
getFileName(filePath) {
  if (!filePath) return '';
  // 处理路径，获取文件名
  const pathParts = filePath.split('/');
  let fileName = pathParts[pathParts.length - 1];
  // 移除时间戳后缀（根据你的文件命名格式）
  fileName = fileName.replace(/_[\d]{14}[A-Z][\d]{3}/, '');
  return fileName;
},

// 文件预览方法
previewFile(filePath) {
  if (!filePath) return;

  // 获取文件完整URL
  const fullUrl = this.getFullFileUrl(filePath);

  // 获取文件扩展名
  const fileExtension = this.getFileExtension(filePath);

  // 只有PDF文件预览，其他都下载
  if (fileExtension === 'pdf') {
    this.previewPdf(fullUrl);
  } else {
    this.downloadFile(fullUrl, filePath);
  }
},

// 获取完整文件URL
getFullFileUrl(filePath) {
  // 如果已经是完整URL则直接返回
  if (filePath.startsWith('http')) {
    return filePath;
  }

  // 处理路径格式
  let processedPath = filePath;
  if (!processedPath.startsWith('/')) {
    processedPath = '/' + processedPath;
  }

  // 获取基础API地址
  const baseApi = process.env.VUE_APP_BASE_API;
  return baseApi + processedPath;
},

// 获取文件扩展名
getFileExtension(filePath) {
  return filePath.split('.').pop().toLowerCase();
},

// PDF预览
previewPdf(url) {
  // 在新窗口打开PDF
  window.open(url, '_blank');
},

// 文件下载
downloadFile(url, originalPath) {
  // 创建隐藏的下载链接
  const link = document.createElement('a');
  link.href = url;
  link.target = '_blank';
  link.download = this.getFileName(originalPath);

  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
    }
  };
</script>